package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.app.application.NineteenApp;
import com.onenine.app.event.GameChatEvent;
import com.onenine.app.event.GameMediaEvent;
import com.onenine.app.model.GameTargetJoin;
import com.onenine.app.utils.Permissions;
import com.onenine.common.util.Logger;
import com.onenine.common.util.SizeUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.rong.calllib.IRongCallListener;
import io.rong.calllib.RongCallClient;
import io.rong.calllib.RongCallCommon;
import io.rong.calllib.RongCallSession;
import io.rong.imlib.model.Conversation;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 语音游戏中
 */
public class GameRunningVoiceActivity extends GameRunningTextActivity
        implements EasyPermissions.PermissionCallbacks, IRongCallListener {

    private final int REQ_AUDIO_PERMISSION = 1;
    private View vVoiceBar;
    private TextView mBtnHandFree, mBtnHangUp;
    private String mCallId;
    private boolean isSpeakOn;

    public static void launchActivity(Context context, String gameUrl
            , String roomId, String uid) {
        Intent intent = new Intent(context, GameRunningVoiceActivity.class);
        intent.putExtra("gameUrl", gameUrl);
        intent.putExtra("roomId", roomId);
        intent.putExtra("uid", uid);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkAudioPermissions();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_game_running_voice;
    }

    @Override
    protected void initViews() {
        super.initViews();
        vVoiceBar = findViewById(R.id.ll_voice_bar);
        mBtnHandFree = findViewById(R.id.tv_hand_free);
        mBtnHangUp = findViewById(R.id.tv_hang_up);
        setVoiceBottomMargin(getResources().getDimensionPixelOffset(R.dimen.game_chat_bar_bottom_margin));
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mBtnHandFree.setOnClickListener(this);
        mBtnHangUp.setOnClickListener(this);
    }

    @Override
    public void keyBoardShow(int height) {
        super.keyBoardShow(height);
        setVoiceBottomMargin(height + SizeUtils.dp2px(20));
    }

    @Override
    public void keyBoardHide(int height) {
        super.keyBoardHide(height);
        setVoiceBottomMargin(getResources().getDimensionPixelOffset(R.dimen.game_chat_bar_bottom_margin));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.tv_hand_free) {
            //免提
            isSpeakOn = !isSpeakOn;
            RongCallClient.getInstance().setEnableSpeakerphone(isSpeakOn);
            mBtnHandFree.setText(isSpeakOn ? R.string.micro_mic : R.string.hand_free);
        } else if (v.getId() == R.id.tv_hang_up) {
            //挂断
            RongCallClient.getInstance().hangUpCall(mCallId);
        }
    }

    /**
     * 设置聊天底部边距
     *
     * @param bottomMargin
     */
    private void setVoiceBottomMargin(int bottomMargin) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) vVoiceBar.getLayoutParams();
        lp.setMargins(0, 0, 0, bottomMargin);
        vVoiceBar.setLayoutParams(lp);
    }

    /**
     * 检查录音权限
     */
    private void checkAudioPermissions() {
        if (!EasyPermissions.hasPermissions(this, Permissions.RECORD_AUDIO_CHAT_PERMISSIONS)) {
            EasyPermissions.requestPermissions(this, getString(R.string.permission_audio_hint)
                    , REQ_AUDIO_PERMISSION, Permissions.RECORD_AUDIO_CHAT_PERMISSIONS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        } else if (requestCode == REQ_AUDIO_PERMISSION) {
            finish();
        }
    }

    @Override
    protected void onTargetJoin(GameTargetJoin targetJoin) {
        super.onTargetJoin(targetJoin);
        if (targetJoin.getJoinIndex() == 1) {
            //目标对手先入者，向其发出语音通话
            convertUid2UserId(targetJoin.getUid(), new OnUid2UserIdResult() {
                @Override
                public void onConvert(String userId) {
                    startAudioCall(userId);
                }
            });
        }
    }

    @Override
    protected void onTargetLeave(GameTargetJoin targetLeave) {
        super.onTargetLeave(targetLeave);
        RongCallClient.getInstance().hangUpCall(mCallId);
    }

    /**
     * 发起语音对话
     *
     * @param targetUseId
     */
    private void startAudioCall(String targetUseId) {
        RongCallClient.getInstance().setVoIPCallListener(this);
        NineteenApp.sHandler.post(new Runnable() {
            @Override
            public void run() {
                RongCallClient.getInstance().startCall(Conversation.ConversationType.PRIVATE
                        , targetUseId, new ArrayList<String>() {
                            {
                                add(targetUseId);
                            }
                        }, null, RongCallCommon.CallMediaType.AUDIO, GAME_TAG);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GameChatEvent event) {
        super.onEvent(event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GameMediaEvent event) {
        if (RongCallCommon.CallMediaType.AUDIO == event.callMediaType) {
            RongCallClient.getInstance().setVoIPCallListener(this);
            RongCallClient.getInstance().acceptCall(event.callId);
        }
    }

    @Override
    public void onCallOutgoing(RongCallSession rongCallSession, SurfaceView surfaceView) {
        Logger.e("游戏语音通话已发送");
    }

    @Override
    public void onCallConnected(RongCallSession rongCallSession, SurfaceView surfaceView) {
        Logger.e("游戏语音通话已连接");
        mCallId = rongCallSession.getCallId();
        vVoiceBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onCallDisconnected(RongCallSession rongCallSession, RongCallCommon.CallDisconnectedReason callDisconnectedReason) {
        Logger.e("游戏语音通话已断开");
        RongCallClient.getInstance().setEnableSpeakerphone(false);
        mCallId = rongCallSession.getCallId();
        vVoiceBar.setVisibility(View.GONE);
    }

    @Override
    public void onRemoteUserRinging(String s) {

    }

    @Override
    public void onRemoteUserJoined(String s, RongCallCommon.CallMediaType callMediaType, int i, SurfaceView surfaceView) {
        Logger.e("游戏语音通话已加入");
    }

    @Override
    public void onRemoteUserInvited(String s, RongCallCommon.CallMediaType callMediaType) {

    }

    @Override
    public void onRemoteUserLeft(String s, RongCallCommon.CallDisconnectedReason callDisconnectedReason) {

    }

    @Override
    public void onMediaTypeChanged(String s, RongCallCommon.CallMediaType callMediaType, SurfaceView surfaceView) {

    }

    @Override
    public void onError(RongCallCommon.CallErrorCode callErrorCode) {

    }

    @Override
    public void onRemoteCameraDisabled(String s, boolean b) {

    }

    @Override
    public void onWhiteBoardURL(String s) {

    }

    @Override
    public void onNetworkReceiveLost(int i) {

    }

    @Override
    public void onNetworkSendLost(int i) {

    }

    @Override
    public void onNotifySharingScreen(String s, boolean b) {

    }

    @Override
    public void onNotifyDegradeNormalUserToObserver(String s) {

    }

    @Override
    public void onNotifyAnswerObserverRequestBecomeNormalUser(String s, long l) {

    }

    @Override
    public void onNotifyUpgradeObserverToNormalUser() {

    }

    @Override
    public void onNotifyHostControlUserDevice(String s, int i, int i1) {

    }

    @Override
    public void onNotifyAnswerUpgradeObserverToNormalUser(String s, SurfaceView surfaceView) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RongCallClient.getInstance().hangUpCall();
        RongCallClient.getInstance().setVoIPCallListener(null);
    }

}
